package com.mybatisplus.service.impl;

import com.mybatisplus.service.SendEmailService;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * @author: GuoZhengrong
 * @Created: 2023/4/24-13:57
 */


/**
 * 调用其中的sendEmail(String someone, String subject, String content)方法
 * 发送普通邮件到指定收件箱
 */
@Service
public class SendEmailImpl implements SendEmailService {
    private static final ResourceBundle bundle = ResourceBundle.getBundle("mail");
    private static final String sendFrom = bundle.getString("email.from");
    private static final String username = bundle.getString("username");
    private static final String password = bundle.getString("password");
    private static final String host = bundle.getString("email.host");

    public void sendEmail(String someone, String subject, String content) throws MessagingException {
        Properties props = new Properties();
        props.setProperty("mail.host", host);
        props.setProperty("mail.smtp.auth", "true");

        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
        Session session = Session.getDefaultInstance(props, authenticator);
        session.setDebug(true);
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(sendFrom));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(someone));
        //message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=UTF-8");
        Transport.send(message);

    }

}
